<template>
  <div class="collection_wrap processed_wrap" @click="chatFunctionActive = false">
    <div :class="['processed_head', { processed_head_fold: isFoldCreated }]">
      <div class="processed_head_item processed_head_type">
        <el-select class="my_el_select" style="margin: 0" v-model="typeSel" placeholder="全部">
          <el-option label="全部" value="0"></el-option>
          <el-option label="文本" value="1"></el-option>
          <el-option label="文件" value="2"></el-option>
          <el-option label="图片" value="3"></el-option>
          <el-option label="音频" value="4"></el-option>
          <el-option label="视频" value="5"></el-option>
          <el-option label="文章" value="6"></el-option>
        </el-select>
      </div>
      <div class="processed_head_item">
        <el-input class="my_el_select" v-model="colcSearch" placeholder="请输入关键字" maxlength="15"
          suffix-icon="el-icon-search" clearable @keyup.enter.native="collectSearchFn" @change="collectSearchFn">
        </el-input>
      </div>
      <div class="processed_head_item_fold" v-if="!isFold" @click.stop.prevent="isFoldCreated = !isFoldCreated">
        <div class="processed_head_item_fold_l">
          {{ !isFoldCreated ? "更多" : "收起" }}
        </div>
        <div class="processed_head_item_fold_r">
          <img v-if="!isFoldCreated" src="static/image/home/chat/remote_fold_orange.png" />
          <img v-else src="static/image/home/chat/remote_open_orange.png" />
        </div>
      </div>
    </div>
    <div :class="['processed_head', { processed_head_fold_m: isFoldCreated }]" v-if="isFoldCreated">
      <div class="processed_head_item processed_head_item_time">
        <div class="processed_head_item_type">收藏</div>
        <el-date-picker class="my_el_select my_el_select_time" v-model="colcTime" type="daterange" align="right"
          unlink-panels value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" :picker-options="$store.state.pickerOptions" @change="remindSearchFn">
        </el-date-picker>
      </div>
      <div class="processed_head_item processed_head_item_time">
        <div class="processed_head_item_type">消息</div>
        <el-date-picker class="my_el_select my_el_select_time" v-model="mesgTime" type="daterange" align="right"
          unlink-panels value-format="timestamp" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          :picker-options="$store.state.pickerOptions" @change="remindSearchFn">
        </el-date-picker>
      </div>
    </div>
    <div class="colc_main">
      <template v-for="(item, index) in collectList">
        <div class="collection_item" :key="'coll' + index" @click.stop.prevent="collectionItemClik(item)"
          @contextmenu.stop.prevent='chatFunctionCt($event, item)'>

          <div class="coll_item_l">
            <div class="colc_content">
              <div class="c_image" v-if="item.FILE_TYPE == 'image'">
                <div class="c_img_head">
                  {{ JSON.parse(item.VALUE).name }}
                </div>
                <div class="c_img_main images" v-viewer="{ navbar: false, toolbar: false }">
                  <img viewer="true" draggable="false" :src="get_inline_img(item.FILE_ID)" :onerror="errorImg" />
                </div>
              </div>
              <div class="c_file" v-else-if="item.FILE_TYPE == 'file'">
                <div class="c_file_icon">
                  <img v-lazy="$utilJs.getFileType(JSON.parse(item.VALUE).fileName)" />
                </div>
                <div class="c_file_main">
                  <div class="c_file_value">
                    {{ JSON.parse(item.VALUE).fileName }}
                  </div>
                  <div class="c_file_size">
                    {{ JSON.parse(item.VALUE).fileSize | convertByte }}
                  </div>
                  <Progress v-if="item.upload == 1" :percent="item.progress ? item.progress : 0"
                    status="active"></Progress>
                </div>
              </div>
              <div class="c_text" v-else-if="item.FILE_TYPE == 'text'">
                <div class="c_text_name" v-if="item.TYPE == '1'">
                  {{ JSON.parse(item.VALUE).name }}
                </div>
                <div class="c_text_value" v-html="JSON.parse(item.VALUE).content"></div>
              </div>
              <div class="c_audio" v-else-if="item.FILE_TYPE == 'audio'"
                @click.stop.prevent="toPlayAudio(JSON.parse(item.VALUE))">
                <!-- zk18注释，收藏的语音不显示文字 -->
                <!-- <div class="c_audio_name">
                          {{ JSON.parse(item.VALUE).name }}
                        </div> -->
                <div class="c_audio_play">
                  <div class="c_audio_p_info">
                    <img draggable="false" src="static/image/home/ease_chatfrom_voice_playing.png"
                      :ref="`audio_${JSON.parse(item.VALUE).messageId}`" />
                    <div>{{ JSON.parse(item.VALUE).fileSize }}s</div>
                  </div>
                  <!-- zk18注释，收藏的语音不再显示文字 -->
                  <!-- <div
                            v-show="JSON.parse(item.VALUE).fileName"
                            class="chat_audio_text"
                          >
                            {{ JSON.parse(item.VALUE).fileName }}
                          </div> -->
                  <!-- 修改后 -->
                  <audio :src="JSON.parse(item.VALUE).isDownLoad" :ref="JSON.parse(item.VALUE).messageId"
                    @ended="init_auto_play"></audio>
                </div>
              </div>
              <div class="c_video" v-else-if="item.FILE_TYPE == 'video'" @click.stop="toPreviewFile(item, 1)">
                <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
                  :options="playerOptions[JSON.parse(item.VALUE).messageId]"></video-player>
              </div>
              <div class="c_article" v-else-if="item.FILE_TYPE == 'article' && JSON.parse(item.VALUE).title"
                @click.stop.prevent="openLinkFn(JSON.parse(item.VALUE))">
                <div :class="[
                  'c_article_l',
                  {
                    c_article_l_r: $isNull(JSON.parse(item.VALUE).picture),
                  },
                ]">
                  <div class="c_article_l_t">
                    {{
                      JSON.parse(item.VALUE).title.length > 50
                        ? JSON.parse(item.VALUE).title.substring(0, 50) + "..."
                        : JSON.parse(item.VALUE).title
                    }}
                  </div>
                  <div class="c_article_l_p">
                    {{
                      JSON.parse(item.VALUE).describe.length > 50
                        ? JSON.parse(item.VALUE).describe.substring(0, 50) +
                        "..."
                        : JSON.parse(item.VALUE).describe
                    }}
                  </div>
                </div>
                <div class="c_article_r" v-if="!$isNull(JSON.parse(item.VALUE).picture)">
                  <img :src="
                    $store.state.url +
                    'api/v1/oim/image/download.do?id=' +
                    JSON.parse(item.VALUE).picture
                  " />
                </div>
              </div>
            </div>
            <div :class="[
              'colc_handle',
              { colc_handle_article: item.FILE_TYPE == 'article' },
            ]" v-if="item.upload != 1">
              <div class="colc_handel_item">
                <!-- zk0204新增，收藏的视频也显示下载 ||item.FILE_TYPE == 'video'-->
                <Tooltip content="文件下载" placement="left" style="margin-right: 15px" v-if="
                  (item.FILE_TYPE == 'file' || item.FILE_TYPE == 'video') && (item.collectFilePath === null ? true : item.collectFilePath ? false : JSON.parse(item.VALUE).content.indexOf('/') < 0 ? true : false)

                ">
                  <span class="colc_down" @click.stop.prevent="ColDownFile(item, 1)"></span>
                </Tooltip>
                <Tooltip content="文件预览" placement="left" style="margin-right: 15px"
                  v-else-if="item.FILE_TYPE == 'file' || item.FILE_TYPE == 'video'">
                  <span class="colc_preview" @click.stop.prevent="collectPreviewFile(item)"></span>
                </Tooltip>
                <Tooltip content="图片下载" placement="left" style="margin-right: 15px" v-if="item.FILE_TYPE == 'image'">
                  <span class="colc_down" @click.stop.prevent="ColtoDownImg(item)"></span>
                </Tooltip>
                <Tooltip content="删除收藏" placement="right">
                  <span class="c_del_icon" @click.stop.prevent="delCollect(item.MESSAGE_ID, index)"></span>
                </Tooltip>
              </div>
            </div>
          </div>
          <div class="coll_item_r">
            <div>{{ item.CREATEDATE }}</div>
            <div>
              来自<span>{{ item.FROM_NAME }}</span>
            </div>
          </div>
        </div>
      </template>
    </div>
    <div class="page_box" v-show="collectTotal > pageSize">
      <Page class="page_main" :total="collectTotal" show-total :current="files_cur" :page-size="pageSize"
        @on-change="pageChange"></Page>
      <div class="page_foot page_foot_home">
        <div>跳转至</div>
        <input type="number" :min="1" v-model.number="page_num" />页&nbsp;<button @click.stop.prevent="goPage">
          确定
        </button>
      </div>
    </div>
    <!-- 收藏文本信息查看 -->
    <div class="collect_text_view" v-if="collectionItem" @click.stop.prevent="">
      <div class="collect_head">
        <div class="c_t_v_close" @click.stop="collectionItem=null"></div>
        <div class="c_t_v_l">
          来自<span>{{ collectionItem.FROM_NAME }}</span>
        </div>
        <div class="c_t_v_r">收藏于{{ collectionItem.CREATEDATE }}</div>
      </div>
      <div class="collect_text_main">
        <div class="collect_text_item">
          <div class="coll_t_head">
            <img :src="
              !$isNull(collectionItem.head)
                ? `${$store.state.headPathUrl}${collectionItem.id}${collectionItem.head}.PNG`
                : `static/image/home/person_${collectionItem.gender == 1 ? 1 : 2
                }.png`
            " :onerror="defaultImg" />
            <!-- <img :src="!$isNull(collectionItem.headPath)?(collectionItem.headPath):`static/image/home/person_${collectionItem.gender==1?1:2}.png`" :onerror="defaultImg"/> -->
          </div>
          <div class="coll_t_main">
            <div class="coll_text_name">
              {{ JSON.parse(collectionItem.VALUE).name }}
            </div>
            <!-- 修改前 -->
            <div class="coll_text_value" v-html="JSON.parse(collectionItem.VALUE).content"></div>
            <!-- 修改后 -->
          </div>
        </div>
      </div>
    </div>
    <div class="chat_function" @click.stop.prevent="" v-if="chatFunctionActive"
      :style='{ top: chatMenuTop + "px", left: chatMenuLeft + "px" }' @mouseleave="showToForwardingClose()">
      <li class='chat_function_item' @click.stop.prevent='savePicture(currentChatItem)'
        v-if='currentChatItem.type == "image"'>下载</li>
      <li class='main_chat_function'
        v-if='(currentChatItem.FILE_TYPE == "text" || currentChatItem.FILE_TYPE == "image") || ((currentChatItem.type == "file") && (currentChatItem.isDownLoad != 404 && currentChatItem.isDownLoad != 0))'
        @click.stop.prevent='toCopyChat(currentChatItem)'>复制</li>
      <div v-if="currentChatItem.isDownLoad != 404">
        <li class='chat_function_item' v-if="currentChatItem.FILE_TYPE != 'announcement' &&
        currentChatItem.FILE_TYPE != 'screen'" @click.stop.prevent='toForwarding(currentChatItem)'>转发
        </li>
      </div>
    </div>
  </div>

</template>
<script>
import { mapState } from "vuex";
export default {
  components: {},
  props: {
    downLoadHeadPath: {
      type: Function,
    },
    toInfo: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      typeSel: "全部类型",
      collectTotal: 0, // 新增我的收藏列表总条数
      collectionItem: null, //收藏单条数据
      collectList: [], //收藏列表
      collectionType: [
        {
          key: 0,
          label: "全部类型",
        },
        {
          key: 1,
          label: "文本类型",
        },
        {
          key: 2,
          label: "文件类型",
        },
        {
          key: 3,
          label: "音频类型",
        },
        {
          key: 4,
          label: "语音类型",
        },
        {
          key: 5,
          label: "视频类型",
        },
      ],
      colcSearch: null,
      colcTime: [],
      mesgTime: [],
      isFold: false,
      isFoldCreated: false,
      files_cur: 1, //文件当前页数
      pageSize: 10, //每页显示条数
      page_num: 1, //分页
      defaultImg: `this.src='static/image/home/person_1.png'`,
      errorImg: 'this.src="static/image/home/document.png"',
      chatMenuTop: 0,
      chatMenuLeft: 0,
      currentChatItem: {},
      currentTextCopy: "",
      chatFunctionActive: false,
    };
  },
  watch: {
    colcTime: {
      handler(newValue, oldValue) {
        this.collectSearchFn();
      },
    },
    mesgTime: {
      handler(newValue, oldValue) {
        this.collectSearchFn();
      },
    },
    typeSel() {
      this.collectSearchFn();
    },
  },
  computed: {
    ...mapState(["myInfo", "broadType"]),
    sqlTable() {
      return {
        userInformation: `user_information_${this.myInfo.id}`, //用户信息表
        messageList: `message_list_${this.myInfo.id}`, //群聊消息表
        privateList: `private_list_${this.myInfo.id}`, //单聊消息表
        collectList: `collect_list_${this.myInfo.id}`, //我的收藏
      };
    },
    broadList: {
      get() {
        return this.$store.state.broadList;
      },
      set(val) {
        this.$store.commit("setBroadList", val);
      },
    },
  },
  //过滤器filter
  filters: {
    convertByte(byteCount) {
      var count = parseFloat(byteCount || 0),
        unitArr = ["b", "Kb", "Mb", "Gb", "Tb"],
        index = 0;
      if (!count) return 0;
      for (let i = 0; i < 5; i++) {
        if (count >= 1024) {
          count = count / 1024;
          index++;
        } else {
          return index > 0
            ? count.toFixed(2) + unitArr[index]
            : count + unitArr[index];
        }
        if (index == 4) {
          return count.toFixed(2) + unitArr[index];
        }
      }
    },
  },
  methods: {
    toForwarding(temp) {
      console.log("转发内容", temp);
      let obj = JSON.parse(temp.VALUE);
      obj.value = obj.fileName;
      obj.type = temp.FILE_TYPE;
      this.chatFunctionActive = false;
      this.$emit("toForwarding", obj);
    },
    //复制功能
    toCopyChat(item) {
      console.log(item, "点击复制的item");
      this.chatFunctionActive = false;
      if (item.FILE_TYPE == "text") {
        let str = JSON.parse(item.VALUE).content;
        if (item.TYPE == "1") {
          str = JSON.parse(item.VALUE).name;
        }
        const value = this.$utilJs.htmlDecodeByRegExp(
          this.$utilJs.returnEncodeBr(str)
        );
        if (this.currentTextCopy) {
          this.$store.state.copyValue = this.currentTextCopy;
        } else {
          this.$store.state.copyValue = value;
        }
        console.log(this.$store.state.copyValue, "存入仓库的内容");
      } else if (item.FILE_TYPE == "image" || item.FILE_TYPE == "file") {
        //新增会话复制图片文件功能
        const type = item.FILE_TYPE == "image" ? "Bitmap" : "FileDrop";
        const data = JSON.parse(item.VALUE).fileName;

        let msg = this.$shell("SetClipboardData", [
          type,
          this.$isRelativePath(data),
        ]);

        let infs = eval("(" + msg + ")");


        if (infs.return_code == 'INVALID') {
          console.log(item,'需要重新下载图片');
          this.downPic(item,this.myInfo,JSON.parse(item.VALUE).DownLoadId).then(res =>{

            let msg = this.$shell("SetClipboardData", [
                type,
                this.$isRelativePath(res),
              ]);



              if (eval("(" + msg + ")").return_code == 'TRUE') {
                this.$Message.warning("内容已复制到粘贴板");

              }



          })

        }


        this.$store.state.copyValue = null; //zk新增，复制文件和图片时，copyvalue为空
      }

      // 到粘贴板
      this.$copyText(this.$store.state.copyValue).then(
        (e) => {
          // success
          console.log(e, "成功");
          this.$Message.warning("内容已复制到粘贴板");
        },
        (e) => {
          // faile
          console.log(e, "失败");
        }
      );
    },

    // 下载原图
    downPic (item,myInfo,downId) {
      let tempPic = "";
      let _this = this;

      return  new Promise((resolve)=>{

    //zk修改，下载原图rawvalue
    this.$downLoad(
      "api/v1/oim/image/download.do",
      downId,
      wt => {
        var fileReader = new FileReader();
        fileReader.onload = function(w) {
          let base64 = w.target.result.replace(/^data\:.{1,40}base64\,/gi, "");

          let info = _this.$shell("SaveFileStreamczs", [
            myInfo.id,
            downId,
            'jpeg',
            base64,
            0
          ]);
          info = JSON.parse(info);
          tempPic = info.return_msg;


          resolve(tempPic)

        };
        fileReader.readAsDataURL(wt);
      },
      wt => {
        console.log("error");
        console.log(wt);
      }
    );



  })
    },
    //获取坐标
    getItemCoordinate(e) {
      this.chatMenuTop = e.clientY + 2 || 0;
      this.chatMenuLeft = e.clientX + 10 || 0;
    },
    // 会话功能
    chatFunctionCt($event, item) {
      console.warn(item);
      if (this.activeIndex == 1) return;
      this.currentChatItem = item;
      this.currentTextCopy = window.getSelection().toString();
      this.chatFunctionActive = true;
      this.getItemCoordinate($event);
    },
    showToForwardingClose() {
      this.isShowForward = false;
    },
    // 我的收藏筛选
    collectSearchFn() {
      let str = "";
      switch (parseInt(this.typeSel)) {
        case 1:
          str = ` cl.FILE_TYPE = 'text'`;
          break;
        case 2:
          str = ` cl.FILE_TYPE = 'file'`;
          break;
        case 3:
          str = ` cl.FILE_TYPE = 'image'`;
          break;
        case 4:
          str = ` cl.FILE_TYPE = 'audio'`;
          break;
        case 5:
          str = ` cl.FILE_TYPE = 'video'`;
          break;
        case 6:
          str = ` cl.FILE_TYPE = 'article'`;
          break;
      }
      const resTemp = this.collectSQL(str);

      console.log(str);
      console.log(resTemp.list);
      this.collectTotal = resTemp.total.list[0].total;
      this.collectList = this.deleteCollectFormatError(resTemp.list);
      // this.collectList = resTemp.list;
      // 如果type是视频、音频时，显示视频、音频的文件
      if (this.typeSel == 5) {
        // 视频
        let arr = this.screenVideoAudio("video");
        console.log(arr, "arrarrarrarr");
        this.collectList = this.collectList.concat(arr);
      } else if (this.typeSel == 4) {
        // 视频
        let arr = this.screenVideoAudio("audio");
        this.collectList = this.collectList.concat(arr);
      }
      this.$forceUpdate();
    },
    // 收藏查询语句
    collectSQL(str) {
      let pageSizeStart =
        this.files_cur == 1 ? 0 : (this.files_cur - 1) * this.pageSize;
      let ct1 = "",
        ct2 = "",
        mt1 = "",
        mt2 = "";
      if (this.colcTime) {
        ct1 = this.colcTime[0];
        ct2 = this.colcTime[1];
      }
      if (this.mesgTime) {
        mt1 = this.mesgTime[0];
        mt2 = this.mesgTime[1];
      }
      //创建时间
      if (ct1) {
        str += (str == "" ? "" : " AND ") + " CL.CREATEDATE >= '" + ct1 + "' ";
      }
      if (ct2) {
        str += (str == "" ? "" : " AND ") + " CL.CREATEDATE <= '" + ct2 + "' ";
      }
      //消息时间
      if (mt1) {
        str +=
          (str == "" ? "" : " AND ") +
          "( PL.time >= '" +
          mt1 +
          "' OR  ML.time >= '" +
          mt1 +
          "' )";
      }
      if (mt2) {
        str +=
          (str == "" ? "" : " AND ") +
          " ( PL.time <= '" +
          mt2 +
          "' OR ML.time <= '" +
          mt2 +
          "' )";
      }
      // 2022/5/12 zc修改 查表需关联上cl表格
      if (this.colcSearch) {
        str +=
          (str == "" ? "" : " AND ") +
          " (PL.value LIKE '%" +
          this.colcSearch +
          "%' OR  ml.value LIKE '%" +
          this.colcSearch +
          "%' OR  cl.value LIKE '%" +
          this.colcSearch +
          "%')";
      }
      //判断条件不为空加where关键字
      if (str != "") {
        str = " WHERE " + str;
      }
      let total = this.$operationalDatabase(
        `SELECT
          count(1) total
        FROM
          ${this.sqlTable.collectList} cl
          left join  ${this.sqlTable.privateList} pl
          ON cl.MESSAGE_ID = pl.messageId
          left join  ${this.sqlTable.messageList} ml
          ON cl.MESSAGE_ID = ml.messageId
          ${str};`,
        1
      );
      let strSql = `SELECT
          cl.*
          FROM ${this.sqlTable.collectList} cl
          left join  ${this.sqlTable.privateList} pl
          ON cl.MESSAGE_ID = pl.messageId
          left join  ${this.sqlTable.messageList} ml
          ON cl.MESSAGE_ID = ml.messageId
          ${str}
          ORDER BY CREATEDATE DESC LIMIT '${pageSizeStart}', '${this.pageSize}';`;
      let data = this.$operationalDatabase(strSql, 1);

      // console.log('查询==>',strSql)
      return {
        total: total,
        list: data && data.list,
      };
    },
    // 收藏去除格式不正确的项
    deleteCollectFormatError(arr) {
      for (let i in arr) {
        if (typeof arr[i].VALUE == "string") {
          // if (arr[i].VALUE.includes("parseInt")) {
          //   //去除微信不正确格式
          //   console.log(arr[i])
          //   arr.splice(i, 1);
          // }
          try {
            var obj = JSON.parse(arr[i].VALUE);
            if (typeof obj != "object" && obj) {
              arr.splice(i, 1);
            }
          } catch (e) {
            console.log("error：" + arr[i] + "!!!");
          }
        }
      }
      return arr;
    },
    // 收藏筛选如果type是视频、音频时，显示视频、音频的文件
    screenVideoAudio(type) {
      let arrVideo = [],
        arrAudio = [];
      let fileList = this.collectSQL(` cl.FILE_TYPE = 'file'`).list;
      fileList = this.deleteCollectFormatError(fileList);
      for (let i in fileList) {
        let fileName = JSON.parse(fileList[i].VALUE).fileName;
        let type = this.getFileType(
          fileName.substring(fileName.lastIndexOf(".") + 1)
        );
        if (type == "type_video") {
          // 视频
          arrVideo.push(fileList[i]);
        } else if (type == "type_voice") {
          // 音频
          arrAudio.push(fileList[i]);
        }
      }
      if (type == "video") return arrVideo;
      else if (type == "audio") return arrAudio;
    },
    //zk125新增，通过后缀名匹配不同的图标
    getFileType(str) {
      str = str.toLowerCase();
      switch (str) {
        case "xls":
        case "xlsx":
          return "type_excel";
        case "exe":
          return "type_exe";
        case "html":
          return "type_html";
        case "pdf":
          return "type_pdf";
        case "ppt":
          return "type_ppt";
        case "jpg":
        case "jpeg":
        case "png":
        case "gif":
          return "type_picture";
        case "rar":
          return "type_rar";
        case "zip":
          return "type_zip";
        case "txt":
          return "type_txt";
        case "mp4":
        case "avi":
        case "mpeg":
        case "mov":
        case "wmv":
        case "rmvb":
        case "3gp":
          return "type_video";
        case "mp3":
        case "wav":
          return "type_voice";
        case "doc":
        case "docx":
          return "type_word";
        default:
          return "file_icon";
      }
    },
    //收藏文本消息查看
    collectionItemClik(item) {
      this.collectionItem = null;
      this.flagHeadType = 8;
      if (item.FILE_TYPE != "text") {
        return;
      }
      //查询数据库是否有当前发送人的信息
      let userData = this.$operationalDatabase(
        `SELECT head,gender FROM ${this.sqlTable.userInformation} WHERE id = '${JSON.parse(item.VALUE).sendId
        }'`,
        1
      );
      if (userData.list.length == 0) {
        this.$ajax(
          "user/getUserInfo.do",
          {
            userid: JSON.parse(item.VALUE).sendId,
          },
          (res) => {
            if (res.result == "200") {
              this.collectionItem = Object.assign(item, {
                id: JSON.parse(item.VALUE).sendId,
                head: res.data.head,
                gender: res.data.gender,
                headPath: null,
              });
              // 新增下载头像
              this.downLoadHeadPath(this.collectionItem);
            }
          },
          (res) => {
            console.log(res, "error");
          }
        );
      } else {
        this.collectionItem = Object.assign(item, {
          head: userData.list[0].head,
          gender: userData.list[0].gender,
          headPath: null,
        });
        // 新增下载头像
        this.downLoadHeadPath(this.collectionItem);
      }
    },
    //删除收藏
    delCollect(id, index) {
      this.$ajax(
        "user/delCollect.do",
        { userid: this.myInfo.id, messageid: id },
        (res) => {
          if (res.result == 200) {
            this.collectList.splice(index, 1);
            this.$operationalDatabase(
              `DELETE FROM ${this.sqlTable.collectList} WHERE MESSAGE_ID = '${id}'`
            );
            this.collectSearchFn();
            this.$Message.success("删除收藏成功");
            this.$forceUpdate();
          } else {
            console.log(res, "删除失败");
          }
        },
        (res) => {
          console.log(res, "删除失败");
        }
      );
    },
    //播放音频初始化
    init_auto_play() {
      this.$refs[
        `audio_${this.audio_item.messageId}`
      ][0].src = `static/image/home/ease_chat${this.audio_item.id == this.myInfo.id ? "to" : "from"
      }_voice_playing.png`;
      clearInterval(this.audio_time);
      this.audio_play = this.audio_item = this.audio_time = null;
    },
    //收藏音频播放
    toPlayAudio(item) {
      let id = this.audio_item ? this.audio_item.messageId : "";
      let src = `static/image/home/ease_chat${this.audio_item && this.audio_item.id == this.myInfo.id ? "to" : "from"
        }_voice_playing.png`;
      clearInterval(this.audio_time);
      this.audio_time = null;
      this.audio_item = item;
      if (this.audio_play) {
        this.$refs[`audio_${id}`][0].src = src;
        this.audio_play.pause();
        if (this.audio_play != this.$refs[item.messageId][0]) {
          this.audio_play.currentTime = 0;
          this.audio_play = this.$refs[item.messageId][0];
          this.audio_play.play();
          this.audio_timer_inter();
        } else {
          this.audio_play = null;
        }
      } else {
        this.audio_play = this.$refs[item.messageId][0];
        this.audio_play.play();
        this.audio_timer_inter();
      }
    },
    audio_timer_inter() {
      let i = 1;
      this.$refs[
        `audio_${this.audio_item.messageId}`
      ][0].src = `static/image/home/ease_chat${this.audio_item.id == this.myInfo.id ? "to" : "from"
      }_voice_playing_f${i}.png`;
      this.audio_time = setInterval(() => {
        i++;
        if (i == 4) i = 1;
        this.$refs[
          `audio_${this.audio_item.messageId}`
        ][0].src = `static/image/home/ease_chat${this.audio_item.id == this.myInfo.id ? "to" : "from"
        }_voice_playing_f${i}.png`;
        this.$forceUpdate();
      }, 330);
    },
    // 收藏下载
    ColDownFile(item, type) {
      let _this = this;
      if (!type && !type == 1) {
        if (!item.DownLoadId) {
          this.$Message.warning("文件上传中,请稍后下载");
          return;
        }
        if (item.loading) {
          this.$Message.warning("下载中,请稍后");
          return;
        }
      }
      this.$emit("downloadListAddProcess", item);
      // 修改后，加了content
      let index = JSON.parse(item.VALUE).fileName.lastIndexOf("/");
      let str = JSON.parse(item.VALUE).fileName.substring(
        index + 1,
        JSON.parse(item.VALUE).fileName.length
      );
      let fileName = str.lastIndexOf("."); //取到文件名开始到最后一个点的长度
      let fileNameLength = str.length; //取到文件名长度
      let fileFormat = str.substring(fileName + 1, fileNameLength); //截
      let path =
        this.$store.state.user_hot_key[5].charAt(
          this.$store.state.user_hot_key[5].length - 1
        ) == "\\"
          ? this.$store.state.user_hot_key[5]
          : this.$store.state.user_hot_key[5] + "\\";
      console.time("下载时间");

      //zk修改收藏下载参数
      let value = JSON.parse(item.VALUE);
      console.log(
        item,
        this.myInfo,
        this.toInfo,
        "收藏下载打印item，myinfo，toinfo"
      );
      let paramsStr; //zk新增，查询参数
      if (this.toInfo.isGroup) {
        //群聊
        paramsStr = `id=${item.FILE_ID}&messageKey=${item.MESSAGE_ID}&userId=${item.USER_ID}&fromid=${value.sendId}&fromname=${value.name}&groupId=${item.FROM_ID}`;
      } else {
        //单聊
        paramsStr = `id=${item.FILE_ID}&messageKey=${item.MESSAGE_ID}&userId=${item.USER_ID}&fromid=${item.FROM_ID}&fromname=${item.FROM_NAME}`;
      }
      let DownLoadPath =
        this.$store.state.url + "api/v1/oim/file/download.do?" + paramsStr;

      let info;
      if (type && type == 1) {
        info = _this.$shell("SaveFileUrl", [
          _this.myInfo.id,
          DownLoadPath,
          item.MESSAGE_ID,
          str,
          fileFormat,
          "",
        ]);
      } else {
        info = _this.$shell("SaveFileUrl", [
          _this.myInfo.id,
          DownLoadPath,
          item.MESSAGE_ID,
          str,
          fileFormat,
          path,
        ]);
      }
      info = JSON.parse(info);
      if (info.return_code == "TRUE") {
        this.$Message.success("文件下载中,请稍后");
        this.$set(item, "progress", 0);
        this.$set(item, "upload", 1);
        console.timeEnd("下载时间");
        this.$set(item, "loading", true);
        this.$forceUpdate();
      }
    },
    // 收藏下载图片
    ColtoDownImg(item) {
      console.lo;
      let _this = this;
      this.$downLoad(
        "api/v1/oim/image/download.do",
        item.FILE_ID,
        (wt) => {
          var fileReader = new FileReader();
          fileReader.onload = function (w) {
            let suffix = JSON.parse(item.VALUE)
              .fileName.split(".")
              .splice(-1)[0];
            let base64 = w.target.result.replace(
              /^data\:.{1,40}base64\,/gi,
              ""
            );
            let info = _this.$shell("SaveFileStream", [
              _this.myInfo.id,
              base64,
              suffix,
            ]);
            info = JSON.parse(info);
            console.log(item.FILE_ID + "." + suffix);
            if (info.return_code == "TRUE") {
              _this.$shell("SaveAS", [
                _this.$isRelativePath(info.return_msg),
                item.FILE_ID + "." + suffix,
              ]);
              _this.$Message.success("图片下载成功");
            }
          };
          fileReader.readAsDataURL(wt);
        },
        (wt) => {
          console.log("error");
          console.log(wt);
        }
      );
    },
    // 收藏预览
    collectPreviewFile(item) {
      // let path = item.collectFilePath ? item.collectFilePath : item.content;
      let path = item.collectFilePath
        ? item.collectFilePath
        : JSON.parse(item.VALUE).content;
      console.log("收藏的文件路径", path);
      let rep = this.$shell("OpenFlieByUrl", [this.$isRelativePath(path)]);
      rep = JSON.parse(rep);
      console.log(rep, "打开文件");
      if (rep.return_code == "FALSE") {
        this.$Message.info("系统找不到指定的文件,请重新下载");
        this.$set(item, "collectFilePath", null);

        console.log(JSON.parse(item.VALUE), 1008);
        this.$forceUpdate();
        console.log(item, 999);
      }
    },
    get_inline_img(id) {
      return this.$store.state.url + "api/v1/oim/image/download.do?id=" + id;
    },
    //翻页
    pageChange(index) {
      this.files_cur = index;
      this.collectSearchFn();
    },
    goPage() {
      let maxPage = Math.ceil(this.collectTotal / this.pageSize);
      if (this.page_num > maxPage || this.page_num < 1) {
        this.$Message.warning("请输入正确页数");
        return;
      }
      this.files_cur = parseInt(this.page_num);
      this.collectSearchFn();
      this.$forceUpdate();
    },
    openLinkFn(articleItem) {
      this.$emit("openLinkFn", articleItem);
    },
  },
  created() { },
  mounted() {
    this.collectSearchFn();
    // this.$emit("getCollect");
  },
};
</script>
<style scoped>

</style>
